package com.le.tester.javaThink.fourth.concurrency;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/12/30 17:04
 * description：CountDown使用,等待所有的Thread中的task 全部完成，不能重置倒计时数，意味的只能使用一次
 * 把同一个步骤的任务并行完成之后，才进行下一步任务
 */

class TaskPortion implements Runnable {

    private static int counter = 0;

    private final int id = counter++;

    private static Random random = new Random(47);

    private final CountDownLatch latch;

    TaskPortion(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            doWork();
            latch.countDown();
        } catch (Exception e) {
            System.out.println("It is exception " + e.getMessage());
        }
    }

    public void doWork() throws InterruptedException {
        TimeUnit.SECONDS.sleep(random.nextInt(2000));
        System.out.println(this + "completed");
    }

    @Override
    public String toString() {
        return "TaskPortion{" +
                "id=" + id +
                ", latch=" + latch +
                '}';
    }
}

class WaitingTask implements Runnable {

    private static int counter = 0;

    private final int id = counter++;

    private final CountDownLatch latch;

    WaitingTask(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            latch.await();
        } catch (Exception e) {
            System.out.println(this + e.getMessage());
        }
    }

    @Override
    public String toString() {
        return "WaitingTask{" +
                "id=" + id +
                ", latch=" + latch +
                '}';
    }
}

public class CountDownLatchDemo {
    static final int SIZE = 100;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(SIZE);
        for (int i = 0; i < 10; i++) {
            exec.execute(new WaitingTask(latch));
        }
        for (int i = 0; i < SIZE; i++) {
            exec.execute(new TaskPortion(latch));
        }
        System.out.println("Launched all tasks");
        exec.shutdown();
    }
}
